package com.yanxi.aop;


import com.yanxi.mapper.OperateLogMapper;
import com.yanxi.pojo.OperateLog;
import com.yanxi.utils.CurrentHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
public class OperationAspect {
    public static final Logger log = LoggerFactory.getLogger(OperationAspect.class);
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.yanxi.anno.Log)")
    public Object logOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        //起始时间
        long startTime = System.currentTimeMillis();
        //执行原始方法
        Object result = joinPoint.proceed();
        //结束时间
        long endTime = System.currentTimeMillis();
        //方法执行耗时
        long costTime = endTime - startTime;

        //构建实体
        OperateLog olog = new OperateLog();
        olog.setOperateEmpId(getCurrentUserId());//操作人
        olog.setOperateTime(LocalDateTime.now());//操作时间
        olog.setClassName(joinPoint.getTarget().getClass().getName());//类名
        olog.setMethodName(joinPoint.getSignature().getName());//方法名
        olog.setMethodParams(Arrays.toString(joinPoint.getArgs()));//方法参数
        olog.setReturnValue(result != null ? result.toString() : "void");//返回值
        olog.setCostTime(costTime);//方法执行耗时

        //记录日志
        log.info("操作日志：{}", olog);
        operateLogMapper.insert(olog);
        return result;
    }

    public Integer getCurrentUserId(){
        return  CurrentHolder.getCurrentId();
    }
}
